package com.b2c.erp.controller;

import com.b2c.entity.DataRow;
import com.b2c.erp.response.ApiResult;
import com.b2c.entity.ErpStockLocationEntity;
import com.b2c.entity.ErpStocktakingInvoiceItem;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.interfaces.wms.ErpStocktakingInvoiceService;
import com.b2c.interfaces.wms.StockLocationService;
import com.b2c.erp.DataConfigObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 库存盘点
 */
@RequestMapping("/stocktaking")
@Controller
public class StocktakingController {
    @Autowired
    private StockLocationService stockLocationService;
    @Autowired
    private ErpStocktakingInvoiceService stocktakingInvoiceService;

    /**
     * 盘点单据list
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String getPurchaseList(Model model, HttpServletRequest request) {
        Integer pageIndex = 1;
        Integer pageSize = DataConfigObject.getInstance().getPageSize();
        if (StringUtils.isEmpty(request.getParameter("page")) == false) {
            try {
                pageIndex = Integer.parseInt(request.getParameter("page"));
            } catch (Exception e) {
            }
        }
        String billNo = request.getParameter("billNo");
        model.addAttribute("billNo", billNo);

        var result = stocktakingInvoiceService.getList(pageIndex,pageSize,billNo);
        model.addAttribute("list", result.getList());
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalSize", result.getTotalSize());

        model.addAttribute("view", "stocktaking_list");
        model.addAttribute("pView", "sj");
//        model.addAttribute("ejcd", "采购");
//        model.addAttribute("sjcd", "采购单列表");

        return "stocktaking_list";
    }

    /**
     * 添加盘点单GET
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String getPurchaseAdd(Model model, HttpServletRequest request) {
        HttpSession session = request.getSession();
//        Integer userId = Integer.parseInt((String) session.getAttribute("userId"));
        String trueName = (String) session.getAttribute("trueName");
        model.addAttribute("trueName", trueName);
        model.addAttribute("time", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        //生成单据编号
        String billNo = "PAN" +  new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
        model.addAttribute("billNo", billNo);


        //仓库列表
        List<ErpStockLocationEntity> houses = stockLocationService.getListByParentId(0);
        model.addAttribute("houses", houses);

        //前台显示多少条数据
        String[] list = new String[20];
        model.addAttribute("list", list);
        //model.addAttribute("list", stockLocationService.localtionNumber());
//        model.addAttribute("housesJSON", JSON.toJSONString(houses));

            model.addAttribute("view", "stocktaking_list");
            model.addAttribute("pView", "pd");

        return "stocktaking_add";
    }

    /**
     * 盘点单POST
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String getPurchaseAddPost(Model model, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object uid = session.getAttribute("userId");
        Integer userId = Integer.parseInt(uid.toString());
        String trueName = (String) session.getAttribute("trueName");

        /***表单信息***/
        Long stockLocationId = Long.parseLong(request.getParameter("stockLocationId"));
        String billNo = request.getParameter("billNo");
        String billDate = request.getParameter("billDate");



        /***商品信息****/
        String[] specNumber = request.getParameterValues("specNumber");//规格编码组合
        String[] specId = request.getParameterValues("specId");//商品规格id组合
        String[] goodsId = request.getParameterValues("goodsId");//
        String[] goodsNumber = request.getParameterValues("goodsNumber");//
        String[] locationId = request.getParameterValues("locationId");//仓库id
        String[] quantity = request.getParameterValues("quantity");//当前库存
        String[] countedQty = request.getParameterValues("countedQty");//盘点库存

        List<ErpStocktakingInvoiceItem> invoiceItems = new ArrayList<>();
        if (specNumber != null && specNumber.length > 0) {
            //循环组合商品信息
            for (int i = 0; i < specNumber.length; i++) {
                if(StringUtils.isEmpty(specNumber[i])==false){
                    //盘点的商品
                    ErpStocktakingInvoiceItem item = new ErpStocktakingInvoiceItem();
                    item.setCurrentQty(Long.parseLong(quantity[i]));
                    item.setCountedQty(Long.parseLong(countedQty[i]));
                    item.setGoods_id(Long.parseLong(goodsId[i]));
                    item.setGoods_number(goodsNumber[i]);
                    item.setGoods_spec_id(Long.parseLong(specId[i]));
                    item.setGoods_spec_number(specNumber[i]);
                    item.setLocationId(Long.parseLong(locationId[i]));
                    invoiceItems.add(item);
                }
            }
            stocktakingInvoiceService.addInvoice(billNo,billDate,stockLocationId,userId,trueName,invoiceItems);
        }


        return "redirect:/stocktaking/list";
    }


    /**
     * 盘点录入
     * @param model
     * @param request
     * @param iid
     * @return
     */
    @RequestMapping(value = "/counted", method = RequestMethod.GET)
    public String stocktakingCounted(Model model, HttpServletRequest request, @RequestParam Long iid) {
        //获取盘点单据
        var invoice = stocktakingInvoiceService.getInvoiceById(iid);
        model.addAttribute("billNo",invoice.getBillNo());
        model.addAttribute("invoiceId",iid);
        model.addAttribute("status",invoice.getStatus());

        var invoiceItems = stocktakingInvoiceService.getInvoiceItemByIid(iid);
        model.addAttribute("list", invoiceItems);


        model.addAttribute("view", "stocktaking_list");
        model.addAttribute("pView", "pd");

        return "stocktaking_counted";
    }

    @RequestMapping(value = "/counted", method = RequestMethod.POST)
    public String stocktakingCountedPost(Model model, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object uid = session.getAttribute("userId");
        Integer userId = Integer.parseInt(uid.toString());
        String trueName = request.getParameter("trueName");//(String) session.getAttribute("trueName");

        /***表单信息***/
        Long invoiceId = Long.parseLong(request.getParameter("invoiceId"));

        /***商品信息****/

        String[] itemId = request.getParameterValues("itemId");//盘点item id
        String[] counted = request.getParameterValues("counted");//盘点的数量
        String[] currentQty = request.getParameterValues("currentQty");//盘点的数量

        List<ErpStocktakingInvoiceItem> invoiceItems = new ArrayList<>();
        if (itemId != null && itemId.length > 0) {
            //循环组合商品信息
            for (int i = 0; i < itemId.length; i++) {
                if(StringUtils.isEmpty(itemId[i])==false){
                    //盘点的商品
                    ErpStocktakingInvoiceItem item = new ErpStocktakingInvoiceItem();
                    item.setId(Long.parseLong(itemId[i]));
                    //Long counted_=Long.parseLong(currentQty[i])-Long.parseLong(counted[i]);
                    item.setCountedQty(Long.parseLong(counted[i]));

                    invoiceItems.add(item);
                }
            }
            stocktakingInvoiceService.countedInvoiceItem(invoiceId,userId,trueName,invoiceItems);
        }


        return "redirect:/stocktaking/list";
    }

    /**
     * 盘点确认AJAX
     * @param model
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/counted_confirm", method = RequestMethod.POST)
    public ApiResult<Integer> countedConfirm(@RequestBody DataRow data, Model model, HttpServletRequest request) {
        if(data.getLong("invoiceId") == 0 )return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数错误，缺少invoiceId");
        HttpSession session = request.getSession();
        Object uid = session.getAttribute("userId");
        Integer userId = Integer.parseInt(uid.toString());
        String trueName = request.getParameter("trueName");
        //if(userId.intValue()!=1) return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "您没有权限确认");

        stocktakingInvoiceService.countedConfirm(data.getLong("invoiceId") ,userId,trueName);
        return new ApiResult<>(0, "SUCCESS");
    }
}
